3 * This is the Postgres database abstraction layer.
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
23 namespace Wikimedia\Rdbms
;
25 use Wikimedia\Timestamp\ConvertibleTimestamp
;
26 use Wikimedia\WaitConditionLoop
;
33 class DatabasePostgres
extends Database
{
38 protected $lastResultHandle = null;
40 /** @var float|string */
41 private $numericVersion = null;
42 /** @var string Connect string to open a PostgreSQL connection */
43 private $connectString;
48 /** @var string[] Map of (reserved table name => alternate table name) */
49 private $keywordTableMap = [];
52 * @see Database::__construct()
53 * @param array $params Additional parameters include:
54 * - keywordTableMap : Map of reserved table names to alternative table names to use
56 public function __construct( array $params ) {
57 $this->port
= $params['port'] ??
false;
58 $this->keywordTableMap
= $params['keywordTableMap'] ??
[];
60 parent
::__construct( $params );
63 public function getType() {
67 public function implicitGroupby() {
71 public function implicitOrderby() {
75 public function hasConstraint( $name ) {
76 foreach ( $this->getCoreSchemas() as $schema ) {
77 $sql = "SELECT 1 FROM pg_catalog.pg_constraint c, pg_catalog.pg_namespace n " .
78 "WHERE c.connamespace = n.oid AND conname = " .
79 $this->addQuotes( $name ) . " AND n.nspname = " .
80 $this->addQuotes( $schema );
81 $res = $this->doQuery( $sql );
82 if ( $res && $this->numRows( $res ) ) {
89 protected function open( $server, $user, $password, $dbName, $schema, $tablePrefix ) {
90 # Test for Postgres support, to avoid suppressed fatal error
91 if ( !function_exists( 'pg_connect' ) ) {
92 throw new DBConnectionError(
94 "Postgres functions missing, have you compiled PHP with the --with-pgsql\n" .
95 "option? (Note: if you recently installed PHP, you may need to restart your\n" .
96 "webserver and database)\n"
100 $this->server
= $server;
102 $this->password
= $password;
105 // pg_connect() user $user as the default database. Since a database is *required*,
106 // at least pick a "don't care" database that is more likely to exist. This case
107 // arrises when LoadBalancer::getConnection( $i, [], '' ) is used.
108 'dbname' => strlen( $dbName ) ?
$dbName : 'postgres',
110 'password' => $password
112 if ( $server != false && $server != '' ) {
113 $connectVars['host'] = $server;
115 if ( (int)$this->port
> 0 ) {
116 $connectVars['port'] = (int)$this->port
;
118 if ( $this->flags
& self
::DBO_SSL
) {
119 $connectVars['sslmode'] = 'require';
122 $this->connectString
= $this->makeConnectionString( $connectVars );
124 $this->installErrorHandler();
127 // Use new connections to let LoadBalancer/LBFactory handle reuse
128 $this->conn
= pg_connect( $this->connectString
, PGSQL_CONNECT_FORCE_NEW
);
129 } catch ( Exception
$ex ) {
130 $this->restoreErrorHandler();
134 $phpError = $this->restoreErrorHandler();
136 if ( !$this->conn
) {
137 $this->queryLogger
->debug(
138 "DB connection error\n" .
139 "Server: $server, Database: $dbName, User: $user, Password: " .
140 substr( $password, 0, 3 ) . "...\n"
142 $this->queryLogger
->debug( $this->lastError() . "\n" );
143 throw new DBConnectionError( $this, str_replace( "\n", ' ', $phpError ) );
146 $this->opened
= true;
148 # If called from the command-line (e.g. importDump), only show errors
149 if ( $this->cliMode
) {
150 $this->doQuery( "SET client_min_messages = 'ERROR'" );
153 $this->query( "SET client_encoding='UTF8'", __METHOD__
);
154 $this->query( "SET datestyle = 'ISO, YMD'", __METHOD__
);
155 $this->query( "SET timezone = 'GMT'", __METHOD__
);
156 $this->query( "SET standard_conforming_strings = on", __METHOD__
);
157 $this->query( "SET bytea_output = 'escape'", __METHOD__
); // PHP bug 53127
159 $this->determineCoreSchema( $schema );
160 $this->currentDomain
= new DatabaseDomain( $dbName, $schema, $tablePrefix );
162 return (bool)$this->conn
;
165 protected function relationSchemaQualifier() {
166 if ( $this->coreSchema
=== $this->currentDomain
->getSchema() ) {
167 // The schema to be used is now in the search path; no need for explicit qualification
171 return parent
::relationSchemaQualifier();
174 public function databasesAreIndependent() {
178 public function doSelectDomain( DatabaseDomain
$domain ) {
179 if ( $this->getDBname() !== $domain->getDatabase() ) {
180 // Postgres doesn't support selectDB in the same way MySQL does.
181 // So if the DB name doesn't match the open connection, open a new one
186 $domain->getDatabase(),
187 $domain->getSchema(),
188 $domain->getTablePrefix()
191 $this->currentDomain
= $domain;
198 * @param string[] $vars
201 private function makeConnectionString( $vars ) {
203 foreach ( $vars as $name => $value ) {
204 $s .= "$name='" . str_replace( "'", "\\'", $value ) . "' ";
210 protected function closeConnection() {
211 return $this->conn ?
pg_close( $this->conn
) : true;
214 protected function isTransactableQuery( $sql ) {
215 return parent
::isTransactableQuery( $sql ) &&
216 !preg_match( '/^SELECT\s+pg_(try_|)advisory_\w+\(/', $sql );
221 * @return bool|mixed|resource
223 public function doQuery( $sql ) {
224 $conn = $this->getBindingHandle();
226 $sql = mb_convert_encoding( $sql, 'UTF-8' );
227 // Clear previously left over PQresult
228 while ( $res = pg_get_result( $conn ) ) {
229 pg_free_result( $res );
231 if ( pg_send_query( $conn, $sql ) === false ) {
232 throw new DBUnexpectedError( $this, "Unable to post new query to PostgreSQL\n" );
234 $this->lastResultHandle
= pg_get_result( $conn );
235 if ( pg_result_error( $this->lastResultHandle
) ) {
239 return $this->lastResultHandle
;
242 protected function dumpError() {
246 PGSQL_DIAG_MESSAGE_PRIMARY
,
247 PGSQL_DIAG_MESSAGE_DETAIL
,
248 PGSQL_DIAG_MESSAGE_HINT
,
249 PGSQL_DIAG_STATEMENT_POSITION
,
250 PGSQL_DIAG_INTERNAL_POSITION
,
251 PGSQL_DIAG_INTERNAL_QUERY
,
253 PGSQL_DIAG_SOURCE_FILE
,
254 PGSQL_DIAG_SOURCE_LINE
,
255 PGSQL_DIAG_SOURCE_FUNCTION
257 foreach ( $diags as $d ) {
258 $this->queryLogger
->debug( sprintf( "PgSQL ERROR(%d): %s\n",
259 $d, pg_result_error_field( $this->lastResultHandle
, $d ) ) );
263 public function freeResult( $res ) {
264 if ( $res instanceof ResultWrapper
) {
267 Wikimedia\
suppressWarnings();
268 $ok = pg_free_result( $res );
269 Wikimedia\restoreWarnings
();
271 throw new DBUnexpectedError( $this, "Unable to free Postgres result\n" );
275 public function fetchObject( $res ) {
276 if ( $res instanceof ResultWrapper
) {
279 Wikimedia\
suppressWarnings();
280 $row = pg_fetch_object( $res );
281 Wikimedia\restoreWarnings
();
282 # @todo FIXME: HACK HACK HACK HACK debug
284 # @todo hashar: not sure if the following test really trigger if the object
286 $conn = $this->getBindingHandle();
287 if ( pg_last_error( $conn ) ) {
288 throw new DBUnexpectedError(
290 'SQL error: ' . htmlspecialchars( pg_last_error( $conn ) )
297 public function fetchRow( $res ) {
298 if ( $res instanceof ResultWrapper
) {
301 Wikimedia\
suppressWarnings();
302 $row = pg_fetch_array( $res );
303 Wikimedia\restoreWarnings
();
305 $conn = $this->getBindingHandle();
306 if ( pg_last_error( $conn ) ) {
307 throw new DBUnexpectedError(
309 'SQL error: ' . htmlspecialchars( pg_last_error( $conn ) )
316 public function numRows( $res ) {
317 if ( $res === false ) {
321 if ( $res instanceof ResultWrapper
) {
324 Wikimedia\
suppressWarnings();
325 $n = pg_num_rows( $res );
326 Wikimedia\restoreWarnings
();
328 $conn = $this->getBindingHandle();
329 if ( pg_last_error( $conn ) ) {
330 throw new DBUnexpectedError(
332 'SQL error: ' . htmlspecialchars( pg_last_error( $conn ) )
339 public function numFields( $res ) {
340 if ( $res instanceof ResultWrapper
) {
344 return pg_num_fields( $res );
347 public function fieldName( $res, $n ) {
348 if ( $res instanceof ResultWrapper
) {
352 return pg_field_name( $res, $n );
355 public function insertId() {
356 $res = $this->query( "SELECT lastval()" );
357 $row = $this->fetchRow( $res );
358 return is_null( $row[0] ) ?
null : (int)$row[0];
361 public function dataSeek( $res, $row ) {
362 if ( $res instanceof ResultWrapper
) {
366 return pg_result_seek( $res, $row );
369 public function lastError() {
371 if ( $this->lastResultHandle
) {
372 return pg_result_error( $this->lastResultHandle
);
374 return pg_last_error();
378 return $this->getLastPHPError() ?
: 'No database connection';
381 public function lastErrno() {
382 if ( $this->lastResultHandle
) {
383 return pg_result_error_field( $this->lastResultHandle
, PGSQL_DIAG_SQLSTATE
);
389 protected function fetchAffectedRowCount() {
390 if ( !$this->lastResultHandle
) {
394 return pg_affected_rows( $this->lastResultHandle
);
398 * Estimate rows in dataset
399 * Returns estimated count, based on EXPLAIN output
400 * This is not necessarily an accurate estimate, so use sparingly
401 * Returns -1 if count cannot be found
402 * Takes same arguments as Database::select()
404 * @param string $table
406 * @param string $conds
407 * @param string $fname
408 * @param array $options
409 * @param array $join_conds
412 public function estimateRowCount( $table, $var = '*', $conds = '',
413 $fname = __METHOD__
, $options = [], $join_conds = []
415 $conds = $this->normalizeConditions( $conds, $fname );
416 $column = $this->extractSingleFieldFromList( $var );
417 if ( is_string( $column ) && !in_array( $column, [ '*', '1' ] ) ) {
418 $conds[] = "$column IS NOT NULL";
421 $options['EXPLAIN'] = true;
422 $res = $this->select( $table, $var, $conds, $fname, $options, $join_conds );
425 $row = $this->fetchRow( $res );
427 if ( preg_match( '/rows=(\d+)/', $row[0], $count ) ) {
428 $rows = (int)$count[1];
435 public function indexInfo( $table, $index, $fname = __METHOD__
) {
436 $sql = "SELECT indexname FROM pg_indexes WHERE tablename='$table'";
437 $res = $this->query( $sql, $fname );
441 foreach ( $res as $row ) {
442 if ( $row->indexname
== $this->indexName( $index ) ) {
450 public function indexAttributes( $index, $schema = false ) {
451 if ( $schema === false ) {
452 $schemas = $this->getCoreSchemas();
454 $schemas = [ $schema ];
457 $eindex = $this->addQuotes( $index );
459 foreach ( $schemas as $schema ) {
460 $eschema = $this->addQuotes( $schema );
462 * A subquery would be not needed if we didn't care about the order
463 * of attributes, but we do
465 $sql = <<<__INDEXATTR__
469 i.indoption[s.g] as option,
472 (SELECT generate_series(array_lower(isub.indkey,1), array_upper(isub.indkey,1)) AS g
476 ON cis.oid=isub.indexrelid
478 ON cis.relnamespace = ns.oid
479 WHERE cis.relname=$eindex AND ns.nspname=$eschema) AS s,
485 ON ci.oid=i.indexrelid
487 ON ct.oid = i.indrelid
489 ON ci.relnamespace = n.oid
491 ci.relname=$eindex AND n.nspname=$eschema
492 AND attrelid = ct.oid
493 AND i.indkey[s.g] = attnum
494 AND i.indclass[s.g] = opcls.oid
495 AND pg_am.oid = opcls.opcmethod
497 $res = $this->query( $sql, __METHOD__ );
500 foreach ( $res as $row ) {
513 public function indexUnique( $table, $index, $fname = __METHOD__ ) {
514 $sql = "SELECT indexname FROM pg_indexes WHERE tablename='{$table}'" .
515 " AND indexdef LIKE 'CREATE UNIQUE%(" .
516 $this->strencode( $this->indexName( $index ) ) .
518 $res = $this->query( $sql, $fname );
523 return $res->numRows() > 0;
526 public function selectSQLText(
527 $table, $vars, $conds = '', $fname = __METHOD__, $options = [], $join_conds = []
529 if ( is_string( $options ) ) {
530 $options = [ $options ];
533 // Change the FOR UPDATE option as necessary based on the join conditions. Then pass
534 // to the parent function to get the actual SQL text.
535 // In Postgres when using FOR UPDATE, only the main table and tables that are inner joined
536 // can be locked. That means tables in an outer join cannot be FOR UPDATE locked. Trying to
537 // do so causes a DB error. This wrapper checks which tables can be locked and adjusts it
539 // MySQL uses "ORDER BY NULL" as an optimization hint, but that is illegal in PostgreSQL.
540 if ( is_array( $options ) ) {
541 $forUpdateKey = array_search( 'FOR UPDATE', $options, true );
542 if ( $forUpdateKey !== false && $join_conds ) {
543 unset( $options[$forUpdateKey] );
544 $options['FOR UPDATE'] = [];
549 $alias = key( $toCheck );
550 $name = $toCheck[$alias];
551 unset( $toCheck[$alias] );
553 $hasAlias = !is_numeric( $alias );
554 if ( !$hasAlias && is_string( $name ) ) {
558 if ( !isset( $join_conds[$alias] ) ||
559 !preg_match( '/^(?:LEFT|RIGHT|FULL)(?: OUTER)? JOIN$/i', $join_conds[$alias][0] )
561 if ( is_array( $name ) ) {
562 // It's a parenthesized group, process all the tables inside the group.
563 $toCheck = array_merge( $toCheck, $name );
565 // Quote alias names so $this->tableName() won't mangle them
566 $options['FOR UPDATE'][] = $hasAlias ? $this->addIdentifierQuotes( $alias ) : $alias;
572 if ( isset( $options['ORDER BY'] ) && $options['ORDER BY'] == 'NULL' ) {
573 unset( $options['ORDER BY'] );
577 return parent::selectSQLText( $table, $vars, $conds, $fname, $options, $join_conds );
581 public function insert( $table, $args, $fname = __METHOD__, $options = [] ) {
582 if ( !count( $args ) ) {
586 $table = $this->tableName( $table );
587 if ( !isset( $this->numericVersion ) ) {
588 $this->getServerVersion();
591 if ( !is_array( $options ) ) {
592 $options = [ $options ];
595 if ( isset( $args[0] ) && is_array( $args[0] ) ) {
597 $keys = array_keys( $args[0] );
600 $keys = array_keys( $args );
603 $ignore = in_array( 'IGNORE', $options );
605 $sql = "INSERT INTO $table (" . implode( ',', $keys ) . ') VALUES ';
607 if ( $this->numericVersion >= 9.5 || !$ignore ) {
608 // No IGNORE or our PG has "ON CONFLICT DO NOTHING"
610 foreach ( $rows as $row ) {
616 $sql .= '(' . $this->makeList( $row ) . ')';
619 $sql .= ' ON CONFLICT DO NOTHING';
621 $this->query( $sql, $fname );
623 // Emulate IGNORE by doing each row individually, with savepoints
624 // to roll back as necessary.
625 $numrowsinserted = 0;
627 $tok = $this->startAtomic( "$fname (outer)", self::ATOMIC_CANCELABLE );
629 foreach ( $rows as $row ) {
631 $tempsql .= '(' . $this->makeList( $row ) . ')';
633 $this->startAtomic( "$fname (inner)", self::ATOMIC_CANCELABLE );
635 $this->query( $tempsql, $fname );
636 $this->endAtomic( "$fname (inner)" );
638 } catch ( DBQueryError $e ) {
639 $this->cancelAtomic( "$fname (inner)" );
640 // Our IGNORE is supposed to ignore duplicate key errors, but not others.
641 // (even though MySQL's version apparently ignores all errors)
642 if ( $e->errno !== '23505' ) {
647 } catch ( Exception $e ) {
648 $this->cancelAtomic( "$fname (outer)", $tok );
651 $this->endAtomic( "$fname (outer)" );
653 // Set the affected row count for the whole operation
654 $this->affectedRowCount = $numrowsinserted;
660 protected function makeUpdateOptionsArray( $options ) {
661 if ( !is_array( $options ) ) {
662 $options = [ $options ];
665 // PostgreSQL doesn't support anything like "ignore" for
667 $options = array_diff( $options, [ 'IGNORE' ] );
669 return parent::makeUpdateOptionsArray( $options );
673 * INSERT SELECT wrapper
674 * $varMap must be an associative array of the form [ 'dest1' => 'source1', ... ]
675 * Source items may be literals rather then field names, but strings should
676 * be quoted with Database::addQuotes()
677 * $conds may be "*" to copy the whole table
678 * srcTable may be an array of tables.
679 * @todo FIXME: Implement this a little better (separate select/insert)?
681 * @param string $destTable
682 * @param array|string $srcTable
683 * @param array $varMap
684 * @param array $conds
685 * @param string $fname
686 * @param array $insertOptions
687 * @param array $selectOptions
688 * @param array $selectJoinConds
690 protected function nativeInsertSelect(
691 $destTable, $srcTable, $varMap, $conds, $fname = __METHOD__,
692 $insertOptions = [], $selectOptions = [], $selectJoinConds = []
694 if ( !is_array( $insertOptions ) ) {
695 $insertOptions = [ $insertOptions ];
698 if ( in_array( 'IGNORE', $insertOptions ) ) {
699 if ( $this->getServerVersion() >= 9.5 ) {
700 // Use ON CONFLICT DO NOTHING if we have it for IGNORE
701 $destTable = $this->tableName( $destTable );
703 $selectSql = $this->selectSQLText(
705 array_values( $varMap ),
712 $sql = "INSERT INTO $destTable (" . implode( ',', array_keys( $varMap ) ) . ') ' .
713 $selectSql . ' ON CONFLICT DO NOTHING';
715 $this->query( $sql, $fname );
717 // IGNORE and we don't have ON CONFLICT DO NOTHING, so just use the non-native version
718 $this->nonNativeInsertSelect(
719 $destTable, $srcTable, $varMap, $conds, $fname,
720 $insertOptions, $selectOptions, $selectJoinConds
724 parent::nativeInsertSelect( $destTable, $srcTable, $varMap, $conds, $fname,
725 $insertOptions, $selectOptions, $selectJoinConds );
729 public function tableName( $name, $format = 'quoted' ) {
730 // Replace reserved words with better ones
731 $name = $this->remappedTableName( $name );
733 return parent::tableName( $name, $format );
737 * @param string $name
738 * @return string Value of $name or remapped name if $name is a reserved keyword
740 public function remappedTableName( $name ) {
741 return $this->keywordTableMap[$name] ?? $name;
745 * @param string $name
746 * @param string $format
747 * @return string Qualified and encoded (if requested) table name
749 public function realTableName( $name, $format = 'quoted' ) {
750 return parent::tableName( $name, $format );
753 public function nextSequenceValue( $seqName ) {
754 return new NextSequenceValue;
758 * Return the current value of a sequence. Assumes it has been nextval'ed in this session.
760 * @param string $seqName
763 public function currentSequenceValue( $seqName ) {
764 $safeseq = str_replace( "'", "''", $seqName );
765 $res = $this->query( "SELECT currval('$safeseq')" );
766 $row = $this->fetchRow( $res );
772 public function textFieldSize( $table, $field ) {
773 $table = $this->tableName( $table );
774 $sql = "SELECT t.typname as ftype,a.atttypmod as size
775 FROM pg_class c, pg_attribute a, pg_type t
776 WHERE relname='$table' AND a.attrelid=c.oid AND
777 a.atttypid=t.oid and a.attname='$field'";
778 $res = $this->query( $sql );
779 $row = $this->fetchObject( $res );
780 if ( $row->ftype == 'varchar' ) {
781 $size = $row->size - 4;
789 public function limitResult( $sql, $limit, $offset = false ) {
790 return "$sql LIMIT $limit " . ( is_numeric( $offset ) ? " OFFSET {$offset} " : '' );
793 public function wasDeadlock() {
794 // https://www.postgresql.org/docs/9.2/static/errcodes-appendix.html
795 return $this->lastErrno() === '40P01';
798 public function wasLockTimeout() {
799 // https://www.postgresql.org/docs/9.2/static/errcodes-appendix.html
800 return $this->lastErrno() === '55P03';
803 public function wasConnectionError( $errno ) {
804 // https://www.postgresql.org/docs/9.2/static/errcodes-appendix.html
805 static $codes = [ '08000', '08003', '08006', '08001', '08004', '57P01', '57P03', '53300' ];
807 return in_array( $errno, $codes, true );
810 protected function wasKnownStatementRollbackError() {
811 return false; // transaction has to be rolled-back from error state
814 public function duplicateTableStructure(
815 $oldName, $newName, $temporary = false, $fname = __METHOD__
817 $newNameE = $this->addIdentifierQuotes( $newName );
818 $oldNameE = $this->addIdentifierQuotes( $oldName );
820 $temporary = $temporary ? 'TEMPORARY' : '';
823 "CREATE $temporary TABLE $newNameE " .
824 "(LIKE $oldNameE INCLUDING DEFAULTS INCLUDING INDEXES)",
826 $this::QUERY_PSEUDO_PERMANENT
832 $res = $this->query( 'SELECT attname FROM pg_class c'
833 . ' JOIN pg_namespace n ON (n.oid = c.relnamespace)'
834 . ' JOIN pg_attribute a ON (a.attrelid = c.oid)'
835 . ' JOIN pg_attrdef d ON (c.oid=d.adrelid and a.attnum=d.adnum)'
836 . ' WHERE relkind = \'r\''
837 . ' AND nspname = ' . $this->addQuotes( $this->getCoreSchema() )
838 . ' AND relname = ' . $this->addQuotes( $oldName )
839 . ' AND pg_get_expr(adbin, adrelid) LIKE \'nextval(%\'',
842 $row = $this->fetchObject( $res );
844 $field = $row->attname;
845 $newSeq = "{$newName}_{$field}_seq";
846 $fieldE = $this->addIdentifierQuotes( $field );
847 $newSeqE = $this->addIdentifierQuotes( $newSeq );
848 $newSeqQ = $this->addQuotes( $newSeq );
850 "CREATE $temporary SEQUENCE $newSeqE OWNED BY $newNameE.$fieldE",
854 "ALTER TABLE $newNameE ALTER COLUMN $fieldE SET DEFAULT nextval({$newSeqQ}::regclass)",
862 public function resetSequenceForTable( $table, $fname = __METHOD__ ) {
863 $table = $this->tableName( $table, 'raw' );
864 foreach ( $this->getCoreSchemas() as $schema ) {
866 'SELECT c.oid FROM pg_class c JOIN pg_namespace n ON (n.oid = c.relnamespace)'
867 . ' WHERE relkind = \'r\''
868 . ' AND nspname = ' . $this->addQuotes( $schema )
869 . ' AND relname = ' . $this->addQuotes( $table ),
872 if ( !$res || !$this->numRows( $res ) ) {
876 $oid = $this->fetchObject( $res )->oid;
877 $res = $this->query( 'SELECT pg_get_expr(adbin, adrelid) AS adsrc FROM pg_attribute a'
878 . ' JOIN pg_attrdef d ON (a.attrelid=d.adrelid and a.attnum=d.adnum)'
879 . " WHERE a.attrelid = $oid"
880 . ' AND pg_get_expr(adbin, adrelid) LIKE \'nextval(%\'',
883 $row = $this->fetchObject( $res );
886 'SELECT ' . preg_replace( '/^nextval\((.+)\)$/', 'setval($1,1,false)', $row->adsrc ),
898 * @suppress SecurityCheck-SQLInjection array_map not recognized T204911
900 public function listTables( $prefix = null, $fname = __METHOD__ ) {
901 $eschemas = implode( ',', array_map( [ $this, 'addQuotes' ], $this->getCoreSchemas() ) );
902 $result = $this->query(
903 "SELECT DISTINCT tablename FROM pg_tables WHERE schemaname IN ($eschemas)", $fname );
906 foreach ( $result as $table ) {
907 $vars = get_object_vars( $table );
908 $table = array_pop( $vars );
909 if ( !$prefix || strpos( $table, $prefix ) === 0 ) {
910 $endArray[] = $table;
917 public function timestamp( $ts = 0 ) {
918 $ct = new ConvertibleTimestamp( $ts );
920 return $ct->getTimestamp( TS_POSTGRES );
924 * Posted by cc[plus]php[at]c2se[dot]com on 25-Mar-2009 09:12
925 * to https://secure.php.net/manual/en/ref.pgsql.php
927 * Parsing a postgres array can be a tricky problem, he's my
928 * take on this, it handles multi-dimensional arrays plus
929 * escaping using a nasty regexp to determine the limits of each
932 * This should really be handled by PHP PostgreSQL module
935 * @param string $text Postgreql array returned in a text form like {a,b}
936 * @param string[] $output
937 * @param int|bool $limit
941 private function pg_array_parse( $text, &$output, $limit = false, $offset = 1 ) {
942 if ( $limit === false ) {
943 $limit = strlen( $text ) - 1;
946 if ( $text == '{}' ) {
950 if ( $text[$offset] != '{' ) {
951 preg_match( "/(\\{?\"([^\"\\\\]|\\\\.)*\"|[^,{}]+)+([,}]+)/",
952 $text, $match, 0, $offset );
953 $offset += strlen( $match[0] );
954 $output[] = ( $match[1][0] != '"'
956 : stripcslashes( substr( $match[1], 1, -1 ) ) );
957 if ( $match[3] == '},' ) {
961 $offset = $this->pg_array_parse( $text, $output, $limit, $offset + 1 );
963 } while ( $limit > $offset );
968 public function aggregateValue( $valuedata, $valuename = 'value' ) {
972 public function getSoftwareLink() {
973 return '[{{int:version-db-postgres-url}} PostgreSQL]';
977 * Return current schema (executes SELECT current_schema())
981 * @return string Default schema for the current session
983 public function getCurrentSchema() {
984 $res = $this->query( "SELECT current_schema()", __METHOD__ );
985 $row = $this->fetchRow( $res );
991 * Return list of schemas which are accessible without schema name
992 * This is list does not contain magic keywords like "$user"
995 * @see getSearchPath()
996 * @see setSearchPath()
998 * @return array List of actual schemas for the current sesson
1000 public function getSchemas() {
1001 $res = $this->query( "SELECT current_schemas(false)", __METHOD__ );
1002 $row = $this->fetchRow( $res );
1005 /* PHP pgsql support does not support array type, "{a,b}" string is returned */
1007 return $this->pg_array_parse( $row[0], $schemas );
1011 * Return search patch for schemas
1012 * This is different from getSchemas() since it contain magic keywords
1017 * @return array How to search for table names schemas for the current user
1019 public function getSearchPath() {
1020 $res = $this->query( "SHOW search_path", __METHOD__ );
1021 $row = $this->fetchRow( $res );
1023 /* PostgreSQL returns SHOW values as strings */
1025 return explode( ",", $row[0] );
1029 * Update search_path, values should already be sanitized
1030 * Values may contain magic keywords like "$user"
1033 * @param array $search_path List of schemas to be searched by default
1035 private function setSearchPath( $search_path ) {
1036 $this->query( "SET search_path = " . implode( ", ", $search_path ) );
1040 * Determine default schema for the current application
1041 * Adjust this session schema search path if desired schema exists
1042 * and is not alread there.
1044 * We need to have name of the core schema stored to be able
1045 * to query database metadata.
1047 * This will be also called by the installer after the schema is created
1051 * @param string $desiredSchema
1053 public function determineCoreSchema( $desiredSchema ) {
1054 $this->begin( __METHOD__, self::TRANSACTION_INTERNAL );
1055 if ( $this->schemaExists( $desiredSchema ) ) {
1056 if ( in_array( $desiredSchema, $this->getSchemas() ) ) {
1057 $this->coreSchema = $desiredSchema;
1058 $this->queryLogger->debug(
1059 "Schema \"" . $desiredSchema . "\" already in the search path\n" );
1062 * Prepend our schema (e.g. 'mediawiki') in front
1063 * of the search path
1066 $search_path = $this->getSearchPath();
1067 array_unshift( $search_path,
1068 $this->addIdentifierQuotes( $desiredSchema ) );
1069 $this->setSearchPath( $search_path );
1070 $this->coreSchema = $desiredSchema;
1071 $this->queryLogger->debug(
1072 "Schema \"" . $desiredSchema . "\" added to the search path\n" );
1075 $this->coreSchema = $this->getCurrentSchema();
1076 $this->queryLogger->debug(
1077 "Schema \"" . $desiredSchema . "\" not found, using current \"" .
1078 $this->coreSchema . "\"\n" );
1080 /* Commit SET otherwise it will be rollbacked on error or IGNORE SELECT */
1081 $this->commit( __METHOD__, self::FLUSHING_INTERNAL );
1085 * Return schema name for core application tables
1088 * @return string Core schema name
1090 public function getCoreSchema() {
1091 return $this->coreSchema;
1095 * Return schema names for temporary tables and core application tables
1098 * @return string[] schema names
1100 public function getCoreSchemas() {
1101 if ( $this->tempSchema ) {
1102 return [ $this->tempSchema, $this->getCoreSchema() ];
1105 $res = $this->query(
1106 "SELECT nspname FROM pg_catalog.pg_namespace n WHERE n.oid = pg_my_temp_schema()", __METHOD__
1108 $row = $this->fetchObject( $res );
1110 $this->tempSchema = $row->nspname;
1111 return [ $this->tempSchema, $this->getCoreSchema() ];
1114 return [ $this->getCoreSchema() ];
1117 public function getServerVersion() {
1118 if ( !isset( $this->numericVersion ) ) {
1119 $conn = $this->getBindingHandle();
1120 $versionInfo = pg_version( $conn );
1121 if ( version_compare( $versionInfo['client'], '7.4.0', 'lt' ) ) {
1122 // Old client, abort install
1123 $this->numericVersion = '7.3 or earlier';
1124 } elseif ( isset( $versionInfo['server'] ) ) {
1126 $this->numericVersion = $versionInfo['server'];
1128 // T18937: broken pgsql extension from PHP<5.3
1129 $this->numericVersion = pg_parameter_status( $conn, 'server_version' );
1133 return $this->numericVersion;
1137 * Query whether a given relation exists (in the given schema, or the
1138 * default mw one if not given)
1139 * @param string $table
1140 * @param array|string $types
1141 * @param bool|string $schema
1144 private function relationExists( $table, $types, $schema = false ) {
1145 if ( !is_array( $types ) ) {
1146 $types = [ $types ];
1148 if ( $schema === false ) {
1149 $schemas = $this->getCoreSchemas();
1151 $schemas = [ $schema ];
1153 $table = $this->realTableName( $table, 'raw' );
1154 $etable = $this->addQuotes( $table );
1155 foreach ( $schemas as $schema ) {
1156 $eschema = $this->addQuotes( $schema );
1157 $sql = "SELECT 1 FROM pg_catalog.pg_class c, pg_catalog.pg_namespace n "
1158 . "WHERE c.relnamespace = n.oid AND c.relname = $etable AND n.nspname = $eschema "
1159 . "AND c.relkind IN ('" . implode( "','", $types ) . "')";
1160 $res = $this->query( $sql );
1161 if ( $res && $res->numRows() ) {
1170 * For backward compatibility, this function checks both tables and views.
1171 * @param string $table
1172 * @param string $fname
1173 * @param bool|string $schema
1176 public function tableExists( $table, $fname = __METHOD__, $schema = false ) {
1177 return $this->relationExists( $table, [ 'r', 'v' ], $schema );
1180 public function sequenceExists( $sequence, $schema = false ) {
1181 return $this->relationExists( $sequence, 'S', $schema );
1184 public function triggerExists( $table, $trigger ) {
1186 SELECT 1 FROM pg_class, pg_namespace, pg_trigger
1187 WHERE relnamespace=pg_namespace.oid AND relkind='r'
1188 AND tgrelid=pg_class.oid
1189 AND nspname=%s AND relname=%s AND tgname=%s
1191 foreach ( $this->getCoreSchemas() as $schema ) {
1192 $res = $this->query(
1195 $this->addQuotes( $schema ),
1196 $this->addQuotes( $table ),
1197 $this->addQuotes( $trigger )
1200 if ( $res && $res->numRows() ) {
1208 public function ruleExists( $table, $rule ) {
1209 $exists = $this->selectField( 'pg_rules', 'rulename',
1211 'rulename' => $rule,
1212 'tablename' => $table,
1213 'schemaname' => $this->getCoreSchemas()
1217 return $exists === $rule;
1220 public function constraintExists( $table, $constraint ) {
1221 foreach ( $this->getCoreSchemas() as $schema ) {
1222 $sql = sprintf( "SELECT 1 FROM information_schema.table_constraints " .
1223 "WHERE constraint_schema = %s AND table_name = %s AND constraint_name = %s",
1224 $this->addQuotes( $schema ),
1225 $this->addQuotes( $table ),
1226 $this->addQuotes( $constraint )
1228 $res = $this->query( $sql );
1229 if ( $res && $res->numRows() ) {
1237 * Query whether a given schema exists. Returns true if it does, false if it doesn't.
1238 * @param string $schema
1241 public function schemaExists( $schema ) {
1242 if ( !strlen( $schema ) ) {
1243 return false; // short-circuit
1246 $exists = $this->selectField(
1247 '"pg_catalog"."pg_namespace"', 1, [ 'nspname' => $schema ], __METHOD__ );
1249 return (bool)$exists;
1253 * Returns true if a given role (i.e. user) exists, false otherwise.
1254 * @param string $roleName
1257 public function roleExists( $roleName ) {
1258 $exists = $this->selectField( '"pg_catalog"."pg_roles"', 1,
1259 [ 'rolname' => $roleName ], __METHOD__ );
1261 return (bool)$exists;
1265 * @param string $table
1266 * @param string $field
1267 * @return PostgresField|null
1269 public function fieldInfo( $table, $field ) {
1270 return PostgresField::fromText( $this, $table, $field );
1274 * pg_field_type() wrapper
1275 * @param ResultWrapper|resource $res ResultWrapper or PostgreSQL query result resource
1276 * @param int $index Field number, starting from 0
1279 public function fieldType( $res, $index ) {
1280 if ( $res instanceof ResultWrapper ) {
1281 $res = $res->result;
1284 return pg_field_type( $res, $index );
1287 public function encodeBlob( $b ) {
1288 return new PostgresBlob( pg_escape_bytea( $b ) );
1291 public function decodeBlob( $b ) {
1292 if ( $b instanceof PostgresBlob ) {
1294 } elseif ( $b instanceof Blob ) {
1298 return pg_unescape_bytea( $b );
1301 public function strencode( $s ) {
1302 // Should not be called by us
1303 return pg_escape_string( $this->getBindingHandle(), (string)$s );
1306 public function addQuotes( $s ) {
1307 $conn = $this->getBindingHandle();
1309 if ( is_null( $s ) ) {
1311 } elseif ( is_bool( $s ) ) {
1312 return intval( $s );
1313 } elseif ( $s instanceof Blob ) {
1314 if ( $s instanceof PostgresBlob ) {
1317 $s = pg_escape_bytea( $conn, $s->fetch() );
1320 } elseif ( $s instanceof NextSequenceValue ) {
1324 return "'" . pg_escape_string( $conn, (string)$s ) . "'";
1327 public function makeSelectOptions( $options ) {
1328 $preLimitTail = $postLimitTail = '';
1329 $startOpts = $useIndex = $ignoreIndex = '';
1332 foreach ( $options as $key => $option ) {
1333 if ( is_numeric( $key ) ) {
1334 $noKeyOptions[$option] = true;
1338 $preLimitTail .= $this->makeGroupByWithHaving( $options );
1340 $preLimitTail .= $this->makeOrderBy( $options );
1342 if ( isset( $options['FOR UPDATE'] ) ) {
1343 $postLimitTail .= ' FOR UPDATE OF ' .
1344 implode( ', ', array_map( [ $this, 'tableName' ], $options['FOR UPDATE'] ) );
1345 } elseif ( isset( $noKeyOptions['FOR UPDATE'] ) ) {
1346 $postLimitTail .= ' FOR UPDATE';
1349 if ( isset( $noKeyOptions['DISTINCT'] ) || isset( $noKeyOptions['DISTINCTROW'] ) ) {
1350 $startOpts .= 'DISTINCT';
1353 return [ $startOpts, $useIndex, $preLimitTail, $postLimitTail, $ignoreIndex ];
1356 public function buildConcat( $stringList ) {
1357 return implode( ' || ', $stringList );
1360 public function buildGroupConcatField(
1361 $delimiter, $table, $field, $conds = '', $options = [], $join_conds = []
1363 $fld = "array_to_string(array_agg($field)," . $this->addQuotes( $delimiter ) . ')';
1365 return '(' . $this->selectSQLText( $table, $fld, $conds, null, [], $join_conds ) . ')';
1368 public function buildStringCast( $field ) {
1369 return $field . '::text';
1372 public function streamStatementEnd( &$sql, &$newLine ) {
1373 # Allow dollar quoting for function declarations
1374 if ( substr( $newLine, 0, 4 ) == '$mw$' ) {
1375 if ( $this->delimiter ) {
1376 $this->delimiter = false;
1378 $this->delimiter = ';';
1382 return parent::streamStatementEnd( $sql, $newLine );
1385 public function doLockTables( array $read, array $write, $method ) {
1387 foreach ( $write as $table ) {
1388 $tablesWrite[] = $this->tableName( $table );
1391 foreach ( $read as $table ) {
1392 $tablesRead[] = $this->tableName( $table );
1395 // Acquire locks for the duration of the current transaction...
1396 if ( $tablesWrite ) {
1398 'LOCK TABLE ONLY ' . implode( ',', $tablesWrite ) . ' IN EXCLUSIVE MODE',
1402 if ( $tablesRead ) {
1404 'LOCK TABLE ONLY ' . implode( ',', $tablesRead ) . ' IN SHARE MODE',
1412 public function lockIsFree( $lockName, $method ) {
1413 if ( !parent::lockIsFree( $lockName, $method ) ) {
1414 return false; // already held
1416 // http://www.postgresql.org/docs/9.2/static/functions-admin.html#FUNCTIONS-ADVISORY-LOCKS
1417 $key = $this->addQuotes( $this->bigintFromLockName( $lockName ) );
1418 $result = $this->query( "SELECT (CASE(pg_try_advisory_lock($key))
1419 WHEN 'f' THEN 'f' ELSE pg_advisory_unlock($key) END) AS lockstatus", $method );
1420 $row = $this->fetchObject( $result );
1422 return ( $row->lockstatus === 't' );
1425 public function lock( $lockName, $method, $timeout = 5 ) {
1426 // http://www.postgresql.org/docs/9.2/static/functions-admin.html#FUNCTIONS-ADVISORY-LOCKS
1427 $key = $this->addQuotes( $this->bigintFromLockName( $lockName ) );
1428 $loop = new WaitConditionLoop(
1429 function () use ( $lockName, $key, $timeout, $method ) {
1430 $res = $this->query( "SELECT pg_try_advisory_lock($key) AS lockstatus", $method );
1431 $row = $this->fetchObject( $res );
1432 if ( $row->lockstatus === 't' ) {
1433 parent::lock( $lockName, $method, $timeout ); // record
1437 return WaitConditionLoop::CONDITION_CONTINUE;
1442 return ( $loop->invoke() === $loop::CONDITION_REACHED );
1445 public function unlock( $lockName, $method ) {
1446 // http://www.postgresql.org/docs/9.2/static/functions-admin.html#FUNCTIONS-ADVISORY-LOCKS
1447 $key = $this->addQuotes( $this->bigintFromLockName( $lockName ) );
1448 $result = $this->query( "SELECT pg_advisory_unlock($key) as lockstatus", $method );
1449 $row = $this->fetchObject( $result );
1451 if ( $row->lockstatus === 't' ) {
1452 parent::unlock( $lockName, $method ); // record
1456 $this->queryLogger->debug( __METHOD__ . " failed to release lock\n" );
1461 public function serverIsReadOnly() {
1462 $res = $this->query( "SHOW default_transaction_read_only", __METHOD__ );
1463 $row = $this->fetchObject( $res );
1465 return $row ? ( strtolower( $row->default_transaction_read_only ) === 'on' ) : false;
1469 * @param string $lockName
1470 * @return string Integer
1472 private function bigintFromLockName( $lockName ) {
1473 return \Wikimedia\base_convert( substr( sha1( $lockName ), 0, 15 ), 16, 10 );
1478 * @deprecated since 1.29
1480 class_alias( DatabasePostgres::class, 'DatabasePostgres' );